import { Component } from "react";
import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import "./index.scss";
import "../images/public/style.css";

//公共组件
import LgNavCustomBar from "../../components/navCustomBar";
import LgSearch from "../../components/searchInput";
import LgButton from "../../components/button";
import LgSeleTarget from "../../components/seleTarget";
import LgCheckbox from "../../components/checkbox";
import LgEmptyContent from "../../components/emptyContent";
//个人组件
import PrChooseDevicesItem from "../components/personal/chooseDevicesItem";
import PrPopChooseDevices from "../components/personal/popChooseDevices";

//工具
import { getStorage, getBrowserController } from "../../components/utils";
import MyUtils from "../components/personal/utils";
import getInfo from "../utils/getInfo";

//api
import {
  API_getBuildingBoards, //楼牌
  API_getClassBoards, //班牌
  API_getRadioBroadcasts, //广播终端
} from "../../../network/servers";

interface IndexState {
  breadArr: number[];
  datalist: dataItem[];
  showDatalist: dataItem[];
  indexArr: number[];
  chooseDevices: {
    RadioBroadcasts?: any[];
    buildingBoards?: any[];
    classBoard?: any[];
    devics?: any;
  };
  isPopOpen: boolean;
}
interface ChooseDevicesObj {
  deviceId: String | Number;
  deviceName: String;
  deviceType: Number;
}
interface dataItem {
  /**item名 */
  name: string;
  /**item类型 【1】展示图标 【2】展示选择框(icon不生效) */
  itemType: 1 | 2;
  /**图标 1/楼牌 2/班牌 3/广播终端 */
  iconType?: 1 | 2 | 3;
  /**checkBox状态，0不选，1选中，2半选 ,itemType为2时必传*/
  value?: 0 | 1 | 2;
  /**子项 */
  subData?: dataItem[];
  /**信息储存 */
  Info?: any;
}

if (process.env.TARO_ENV === "weapp") {
  var app = Taro.getApp().$app;
} else if (process.env.TARO_ENV === "h5") {
  // var storage = getStorage()
  var browserController = getBrowserController();
}
const storage = getStorage();

/** 当前是否为：亮亮中学 隐藏老师的楼牌和广播终端 */
function isLLSchoolAndIdentityTeach() {
  const userType = getInfo.getUserType();
  const schoolId = getInfo.getSchoolId();
  if (schoolId === "S-ha0713" && userType == "1") return true;
  return false;
}

  //判断当前是否为院系管理员
 function isCollegeAdmin(){
    let identityCode = getInfo.getIdentityCode()
    let identityInfos = MyUtils.getStorage("userInfo").identityInfos

    let idIndex = identityInfos.findIndex(item => item.identityCode ==identityCode)
    if (idIndex == -1) {//身份列表中没有这个身份
      return false
    }
      
    return identityCode==="IC0009"
  }


function getPersonalDevices(): dataItem[] {
  if (isLLSchoolAndIdentityTeach()) {
    return [{ name: "班牌", itemType: 1, iconType: 2, value: 0, subData: [] }];
  }else if(isCollegeAdmin()){
    return [
      { name: "班牌", itemType: 1, iconType: 2, value: 0, subData: [] },
      { name: "广播终端", itemType: 1, iconType: 3, value: 0, subData: [] },
    ];
  } else {
    return [
      { name: "楼牌", itemType: 1, iconType: 1, value: 0, subData: [] },
      { name: "班牌", itemType: 1, iconType: 2, value: 0, subData: [] },
      { name: "广播终端", itemType: 1, iconType: 3, value: 0, subData: [] },
    ];
  }
}
export default class index extends Component<any, IndexState> {
  constructor(props) {
    super(props);

    this.state = {
      datalist: getPersonalDevices(),
      showDatalist: [],
      breadArr: [],
      indexArr: [],
      isPopOpen: false,
      chooseDevices: {
        RadioBroadcasts: [],
        buildingBoards: [],
        classBoard: [],
      },
    };
    this.onCheckbox = this.onCheckbox.bind(this);

    this.closePop = this.closePop.bind(this);
    this.openPop = this.openPop.bind(this);
    this.deleteChoItem = this.deleteChoItem.bind(this);
  }

  UNSAFE_componentWillMount() {
    let toChooseDevices = MyUtils.getStorage("toChooseDevices");
    let showDatalist = JSON.parse(JSON.stringify(this.state.datalist));

    const { devics, classBoard, RadioBroadcasts, buildingBoards } =
      toChooseDevices;

    // console.log('toChooseDevices',toChooseDevices)
    this.setState(
      {
        showDatalist,
        chooseDevices: {
          devics: devics ? devics : [],
          RadioBroadcasts,
          buildingBoards,
          classBoard,
        },
      },
      () => {
        this.pageInit().then(() => {
          let chooseDevices = this.getChooseDevices();
          this.setState({
            chooseDevices,
          });
        });
      }
    );
  }

  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  /**
   * 对象数组中是否有和该对象键值相同的项
   * @param arr 对象数组
   * @param item 对象
   * @param key 键值
   * @returns boolean true代表对象数组包含这个对象
   */
  useArraySome = (arr, item, key: string) => {
    if (!Array.isArray(arr)) {
      return false;
    }

    return arr.some((child) => child["deviceName"] === item["name"]);
  };

  initChoLibrary = (data, userList) => {
    // console.log(data, userList)
    if (
      !Array.isArray(data) ||
      !data.length ||
      !Array.isArray(userList) ||
      !userList.length
    ) {
      return;
    }

    data.forEach((item: any) => {
      // console.log(item.subData)
      if (this.useArraySome(userList, item, "name")) {
        item.value = 1;
      }
      if (item.subData) {
        this.initChoLibrary(item.subData, userList);
      }
    });
  };

  //网络请求================================
  /**楼牌 */
  api_getBuildingBoards() {
    return new Promise<any>((resolve, reject) => {
      let header = {
        Authorization: getInfo.getToken(),
      };
      API_getBuildingBoards({
        schoolId:getInfo.getSchoolId(),
        timestamp:Date.now()
      }, header).then((res) => {
        console.log("api-楼牌", res);
        if (res.code == 200) {
          let a = 0,
            b = 0,
            c = 0;
          res.data.map((item) => {
            if (item.buildingBoardType == 1) {
              a++;
            } else if (item.buildingBoardType == 2) {
              b++;
            } else if (item.buildingBoardType == 3) {
              c++;
            }
          });
          let buildingBoards: dataItem[] = [];
          if (a > 0) {
            buildingBoards.push({
              name: "楼牌",
              itemType: 2,
              value: 0,
              Info: { deviceId: 1 },
            });
          }
          if (b > 0) {
            buildingBoards.push({
              name: "校牌",
              itemType: 2,
              value: 0,
              Info: { deviceId: 2 },
            });
          }
          if (c > 0) {
            buildingBoards.push({
              name: "互动牌",
              itemType: 2,
              value: 0,
              Info: { deviceId: 3 },
            });
          }
          console.log("buildingBoards", buildingBoards);
          resolve(buildingBoards);
        }
      });
    });
  }
  /**班牌 */
  api_getClassBoards() {
    return new Promise<any>((resolve, reject) => {
      let header = {
        Authorization: getInfo.getToken(),
      };
      let body:any={}
      if(isLLSchoolAndIdentityTeach()){
        body.userId=getInfo.getUserId()
      }

      body.schoolId=getInfo.getSchoolId()
      body.timestamp=Date.now()
      API_getClassBoards(body, header).then((res) => {
        console.log("api-班牌", res);
        if (res.code == 200) {
          let classBoard = res.data.map((item) => {
            return { name: item.boardName, itemType: 2, value: 0, Info: item };
          });
          resolve(classBoard);
        }
      });
    });
  }
  /**广播终端 */
  api_getRadioBroadcasts() {
    return new Promise<any>((resolve, reject) => {
      let params = {
        userId: getInfo.getUserId(),
        token: getInfo.getToken(),
        schoolId: getInfo.getSchoolId(),
      };
      let header = {
        Authorization: getInfo.getToken(),
        "Content-Type": "application/x-www-form-urlencoded",
      };
      API_getRadioBroadcasts(params, header).then((res) => {
        console.log("api-广播终端", res);
        if (res.code == 200) {
          let RadioBroadcasts = res.data.map((item) => {
            // let sub = item.devices.map(item2=>{
            //   return {name:item2.devicesName,itemType:2,value:0,Info:item2}
            // })
            return {
              name: item.buildingName,
              itemType: 2,
              value: 0,
              Info: item,
            };
          });
          resolve(RadioBroadcasts);
        }
      });
    });
  }

  flattenObject = (object: any) => {
    let result: any = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        const element = object[key];
        result = [...result, ...element];
      }
    }

    return result;
  };

  //页面初始化====================================
  pageInit() {
    let devics = this.flattenObject(this.state.chooseDevices);
    Array.isArray(devics) &&
      devics.length &&
      devics.forEach((item) => {
        item.name = item.deviceName;
      });

    return new Promise((resolve, reject) => {
      let promiseArr: any = [];
      const forbidden=isLLSchoolAndIdentityTeach()
      const isCollege=isCollegeAdmin()
      !isCollege&&!forbidden&&promiseArr.push(this.api_getBuildingBoards());
      promiseArr.push(this.api_getClassBoards());
      !forbidden&&promiseArr.push(this.api_getRadioBroadcasts());

      Promise.all(promiseArr).then((result) => {
        let datalist = this.state.datalist;

        result.forEach((i, idx) => {
          Array.isArray(i) &&
            i.length &&
            i.forEach((item) => {
              if (this.useArraySome(devics, item, "name")) {
                item.value = 1;
              }
            });

          datalist[idx].subData = i;
        });

        console.log(datalist)
        resolve(datalist);
      });
    });
  }
  //弹窗=========================================
  closePop() {
    //关闭弹窗
    this.setState({
      isPopOpen: false,
    });
  }
  openPop() {
    //打开弹窗
    this.setState({
      isPopOpen: true,
    });
  }

  changeDataList = (dataList, data) => {
    if (!Array.isArray(dataList) || !dataList.length) {
      return;
    }

    dataList.forEach((item) => {
      if (item.name === data.deviceName) {
        item.value = 0;
      } else if (item.subData) {
        this.changeDataList(item.subData, data);
      }
    });
  };

  deleteChoItem(type, data) {
    //弹窗中移除
    console.log("type:", type, "\n选择要移除的item", data);
    let datalist = this.state.datalist;
    if (type == 1) {
      //楼牌
      datalist[0].subData?.forEach((item) => {
        if (item.Info.deviceId == data.Info.deviceId) {
          item.value = 0;
        }
      });
    } else if (type == 2) {
      //班牌
      datalist[1].subData?.forEach((item) => {
        if (item.Info.boardId == data.Info.boardId) {
          item.value = 0;
        }
      });
    } else if (type == 3) {
      //广播终端
      datalist[2].subData?.forEach((item) => {
        if (item.Info.buildingId == data.Info.buildingId) {
          item.value = 0;
        }
      });
    } else if (type == 4) {
      this.changeDataList(datalist, data);
    }

    this.setState(
      {
        datalist,
      },
      () => {
        let indexArr = this.state.indexArr;
        let chooseDevices = this.getChooseDevices();
        let showDatalistInfo = this.getshowDatalist(datalist, indexArr, 1, []);
        let showDatalist = showDatalistInfo.datalist;
        let breadArr = showDatalistInfo.breadArr;
        this.setState({
          chooseDevices,
          showDatalist,
          breadArr,
        });
      }
    );
  }
  //底部按钮=====================================
  onConfirm() {
    let datalist = this.state.datalist;
    console.log("datalist", datalist);
    let ChooseDevices = this.state.chooseDevices;
    if (
      ChooseDevices.buildingBoards.length +
        ChooseDevices.classBoard.length +
        ChooseDevices.RadioBroadcasts.length ==
      0
    ) {
      Taro.showToast({
        title: "未选择设备",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    let showChoDevArr: string[] = [];

    let buildingBoards: {
      deviceType: number;
      deviceId: number | string;
      deviceName: string;
    }[] = [];
    let classBoard: {
      deviceType: number;
      deviceId: number | string;
      deviceName: string;
    }[] = [];
    let RadioBroadcasts: {
      deviceType: number;
      deviceId: number | string;
      deviceName: string;
    }[] = [];

    ChooseDevices.buildingBoards.map((item) => {
      if (item.value == 1) {
        buildingBoards.push({
          deviceType: 2,
          deviceId: item.Info.deviceId,
          deviceName: item.name,
        });
      }
    });
    ChooseDevices.classBoard.map((item) => {
      if (item.value == 1) {
        classBoard.push({
          deviceType: 1,
          deviceId: item.Info.boardId,
          deviceName: item.name,
        });
      }
    });
    ChooseDevices.RadioBroadcasts.map((item) => {
      if (item.value == 1) {
        RadioBroadcasts.push({
          deviceType: 3,
          deviceId: item.Info.buildingId,
          deviceName: item.name,
        });
      }
    });

    if (buildingBoards.length != 0) {
      if (datalist[0].subData?.length == buildingBoards.length) {
        showChoDevArr.push("全部楼牌");
      } else {
        showChoDevArr.push("部分楼牌");
      }
    }
    if (classBoard.length != 0) {
      console.log("部分班牌", classBoard, "\nasdas");
      if (datalist[1].subData?.length == classBoard.length) {
        showChoDevArr.push("全部班牌");
      } else {
        showChoDevArr.push("部分班牌");
      }
    }
    if (RadioBroadcasts.length != 0) {
      if (datalist[2].subData?.length == RadioBroadcasts.length) {
        showChoDevArr.push("全部广播终端");
      } else {
        showChoDevArr.push("部分广播终端");
      }
    }

    console.log("确定", { buildingBoards, classBoard, RadioBroadcasts });
    MyUtils.setStorage("chooseDevices", {
      buildingBoards,
      classBoard,
      RadioBroadcasts,
      devics: [],
    });
    MyUtils.setStorage("showChoDevArr", showChoDevArr);
    Taro.navigateBack({
      delta: 1,
    });
  }
  getChooseDevices(datalist = this.state.datalist) {
    let buildingBoards = this.devicesFilter(datalist[0].subData, 1);
    let classBoard = this.devicesFilter(datalist[1]?.subData, 2);
    let RadioBroadcasts = this.devicesFilter(datalist[2]?.subData, 3);

    // console.log(
    //   buildingBoards,
    //   classBoard,
    //   RadioBroadcasts,
    //   "getChooseDevices",
    //   datalist
    // );
    return { buildingBoards, classBoard, RadioBroadcasts };
  }
  devicesFilter(datalist, type) {
    //1-楼牌，2-班牌，3-广播终端

    console.log(datalist);
    if (datalist == undefined) {
      return [];
    }
    if (type == 1) {
      //楼牌
      // let buildingBoards:{deviceType:number,deviceId:number|string,deviceName:string}[] = []
      // datalist.map(item=>{
      //   if(item.value == 1){
      //     buildingBoards.push({deviceType:2,deviceId:item.Info.deviceId,deviceName:item.name})
      //     // buildingBoards.push(item)
      //   }
      // })
      let buildingBoards = datalist.filter((item) => {
        return item.value == 1;
      });
      return buildingBoards;
    } else if (type == 2) {
      //班牌
      // let classBoard:{deviceType:number,deviceId:number|string,deviceName:string}[] = []
      // datalist.map(item=>{
      //   if(item.value == 1){
      //     classBoard.push({deviceType:1,deviceId:item.Info.boardId,deviceName:item.name})
      //   }
      // })
      let classBoard = datalist.filter((item) => {
        return item.value == 1;
      });
      return classBoard;
    } else if (type == 3) {
      //广播终端
      // let RadioBroadcasts:{deviceType:number,deviceId:number|string,deviceName:string}[] = []
      // datalist.map(item=>{
      //   if(item.value == 1){
      //     RadioBroadcasts.push({deviceType:3,deviceId:item.Info.buildingId,deviceName:item.name})
      //   }
      // })
      let RadioBroadcasts = datalist.filter((item) => {
        return item.value == 1;
      });
      return RadioBroadcasts;
    } else {
      return [];
    }
  }

  //事件=========================================
  onClickItem(data, index) {
    // console.log("onClickItem", data, index)
    let datalist = this.state.datalist;
    // console.log("datalist", datalist)

    if (data.itemType == 1) {
      //可以进入下一层
      let indexArr = this.state.indexArr;
      indexArr.push(index);
      // console.log("indexArr2", indexArr)
      // let br = this.state.breadArr
      let showDatalistInfo = this.getshowDatalist(datalist, indexArr, 1, []);
      let showDatalist = showDatalistInfo.datalist;
      let breadArr = showDatalistInfo.breadArr;
      // console.log("showDatalist", showDatalist, "\nbreadArr", breadArr)
      this.setState({
        breadArr,
        showDatalist,
      });
    }
  }
  getshowDatalist(datalist, indexArr, level, breadArr) {
    // console.log("breadArr",breadArr)
    if (indexArr.length == 0) {
      return { datalist, breadArr };
    } else {
      if (level - 1 == indexArr.length) {
        return { datalist, breadArr };
      } else {
        breadArr.push(datalist[indexArr[level - 1]].name);
        return this.getshowDatalist(
          datalist[indexArr[level - 1]].subData,
          indexArr,
          level + 1,
          breadArr
        );
      }
    }
  }
  onClickBreadArr(type, index) {
    // console.log("showdatalist", this.state.showDatalist)
    // console.log("datalist", this.state.datalist)
    let datalist = this.state.datalist;
    if (type == 1) {
      //返回根目录
      let dataInfo = this.getshowDatalist(datalist, [], 1, []);
      this.setState({
        indexArr: [],
        showDatalist: dataInfo.datalist,
        breadArr: dataInfo.breadArr,
      });
    } else if (type == 2) {
      let indexArr = this.state.indexArr;
      indexArr.splice(index + 1);
      // console.log("改变之后的indexArr", indexArr)
      let dataInfo = this.getshowDatalist(datalist, indexArr, 1, []);
      this.setState({
        showDatalist: dataInfo.datalist,
        breadArr: dataInfo.breadArr,
      });
    }
  }

  onCheckbox(value, index) {
    let datalist = this.state.datalist;
    let indexArr = this.state.indexArr;
    // console.log("1231232312321321321321")
    let showDatalist = this.changeCheckbox(datalist, indexArr, 1, value, index);
    let chooseDevices = this.getChooseDevices();
    this.setState({
      showDatalist,
      chooseDevices,
    });
  }
  changeCheckbox(datalist, indexArr, level, value, index) {
    if (indexArr.length == 0) {
      datalist[index].value = value;
      return datalist;
    } else {
      if (level - 1 == indexArr.length) {
        datalist[index].value = value;
        return datalist;
      } else {
        return this.changeCheckbox(
          datalist[indexArr[level - 1]].subData,
          indexArr,
          level + 1,
          value,
          index
        );
      }
    }
  }

  //信息获取======================================
  // getToken(){//token获取
  //   if(process.env.TARO_ENV === 'weapp'){
  //     return app.globalData.Token
  //   }else if(process.env.TARO_ENV === 'h5'){
  //     let token = storage.get("token")
  //     if(!token){
  //       let urlToken = MyUtils.getQueryVariable("lg_tk")
  //       return urlToken
  //     }else{
  //       return storage.get("token")
  //     }
  //   }else{
  //     console.log("未配置端,Token获取失败")
  //     return ""
  //   }
  // }
  // getUserId(){//获取用户id
  //   if(process.env.TARO_ENV === 'h5'){
  //     let userInfo = JSON.parse(storage.get("userInfo")) || MyUtils.getStorage("userInfo")?.userId
  //     return userInfo.UserID
  //   }else if(process.env.TARO_ENV === 'weapp'){
  //     return app.globalData.userID
  //   }
  //   return undefined
  // }
  //===================================

  render() {
    let breadArr = this.state.breadArr;
    let showDatalist = this.state.showDatalist;
    let env = getInfo.getEnv();

    return (
      <View className="chooseDevices">
        {env === "weapp" ? (
          ""
        ) : (
          <LgNavCustomBar
            mainTitle={"选择设备"}
            needMainIcon={process.env.TARO_ENV === "weapp" ? false : true}
            needBackIcon={true}
            isTitlePositionLeft={true}
            mainTitleBold={false}
          ></LgNavCustomBar>
        )}
        <View className="chooseDevices_top">
          <View className="breadcrumb_nav">
            <View className="breadcrumb_nav_scroll">
              <View className="breadcrumb_nav_wrap">
                <View
                  className="breadcrumb_nav_item"
                  style={{ color: "rgb(85,85,85)" }}
                >
                  位置：
                </View>
                <View
                  className={`breadcrumb_nav_item ${
                    breadArr.length == 0 ? "colorGrey" : ""
                  }`}
                  onClick={() => this.onClickBreadArr(1, -1)}
                >
                  选择设备
                  {breadArr.length == 0 ? (
                    ""
                  ) : (
                    <View className="icon-b01901"></View>
                  )}
                </View>
                {breadArr.map((item, index) => {
                  return (
                    <View
                      key={"breadcrumb" + index}
                      className={`breadcrumb_nav_item ${
                        breadArr.length == index + 1 ? "colorGrey" : ""
                      }`}
                      onClick={() => {
                        index + 1 == breadArr.length
                          ? ""
                          : this.onClickBreadArr(2, index);
                      }}
                    >
                      {item}
                      {index + 1 == breadArr.length ? (
                        ""
                      ) : (
                        <View className="icon-b01901"></View>
                      )}
                    </View>
                  );
                })}
              </View>
            </View>
          </View>
        </View>

        <View className="fileMove_list">
          <View className="list_part">
            {showDatalist.map((item, index) => {
              let haveSub = true;
              if (item.subData == undefined) {
                haveSub = false;
              }
              return (
                <PrChooseDevicesItem
                  key={"chooseDevice-" + index}
                  index={index}
                  value={item.value}
                  itemType={item.itemType}
                  iconType={item.iconType}
                  onClickItem={() => this.onClickItem(item, index)}
                  onCheckbox={this.onCheckbox}
                  haveSub={haveSub}
                >
                  {item.name}
                </PrChooseDevicesItem>
              );
            })}
            {showDatalist.length == 0 ? (
              <View className="no_contant">
                <LgEmptyContent
                  // imgUrl={require("../images/index/占位图.png")}
                  text={"暂无可选设备"}
                  type="B"
                ></LgEmptyContent>
              </View>
            ) : (
              ""
            )}
          </View>
        </View>

        <View className="chooseDevices_btnBox">
          <View className="text" onClick={this.openPop}>
            已选择设备
          </View>
          <LgButton
            className="btn_chooseDevices"
            type="B"
            onClick={() => this.onConfirm()}
          >
            确定
          </LgButton>
        </View>

        <PrPopChooseDevices
          isOpen={this.state.isPopOpen}
          data={this.state.chooseDevices}
          onClosePop={this.closePop} //关闭弹窗
          deleteItem={this.deleteChoItem} //移除所选
        ></PrPopChooseDevices>
      </View>
    );
  }
}
